/**
 * 
 */
package pers.vic.readmd.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *  @description: 
 *  @author Vic.xu
 *  @date: 2020年5月15日下午2:46:03
 */
@Controller
public class ReadmdController {
	
	String markdownPath;
	
	/**
	 * 前往文档目录页面
	 * @return
	 */
	@RequestMapping("/readme")
	public String list(Model model) throws IOException {

		List<String> files =
		Files.list(Paths.get(markdownPath)).filter(s->s.toString().endsWith(".md")).map(path->path.toFile().getName()).collect(Collectors.toList());
		model.addAttribute("files", files);
		return "index";
	}

	/**
	 * 展示某个具体的文档
	 * @param fileName 文件名
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/readme/{fileName}")
	public String detail(@PathVariable String fileName, Model model) {
		String content;
		try{
			List<String> lines = Files.lines(Paths.get(markdownPath, fileName), StandardCharsets.UTF_8).collect(Collectors.toList());
			content = String.join("\n", lines);
		}catch (Exception e) {
			content = e.getMessage();
		}
		model.addAttribute("content", content);
		return "readme";
	}

}
